package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.alibaba.nacos.api.cmdb.pojo.PreservedEntityTypes.service;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Autowired
    private WxPayV3Config wxPayV3Config;

    /**
     * 微信下单
     * @param paymentType
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, Object> createJsapi(String paymentType, String orderNo) {

        Long userId = AuthContextHolder.getUserId();
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(userId, paymentType, orderNo);

        // 构建service
        JsapiServiceExtension jsapiService = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest prepayRequest = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(1);
        prepayRequest.setAmount(amount);
        prepayRequest.setAppid(wxPayV3Config.getAppid());
        prepayRequest.setMchid(wxPayV3Config.getMerchantId());
        prepayRequest.setDescription(paymentInfo.getContent());
        prepayRequest.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        Payer payer = new Payer();
        payer.setOpenid("odo3j4ujPBRopdATZnxKZ3HDOLAc");
        prepayRequest.setPayer(payer);
        prepayRequest.setOutTradeNo(paymentInfo.getOrderNo());
        PrepayWithRequestPaymentResponse response = jsapiService.prepayWithRequestPayment(prepayRequest);
        if (response != null) {
            Map<String, Object> mapResult = new HashMap<>();
            mapResult.put("timeStamp", response.getTimeStamp());
            mapResult.put("package", response.getPackageVal());
            mapResult.put("paySign", response.getPaySign());
            mapResult.put("signType", response.getSignType());
            mapResult.put("nonceStr", response.getNonceStr());
            return mapResult;
        }
        return null;
    }

    /**
     * 支付状态查询（同步查询）
     * @param orderNo
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Boolean queryPayStatus(String orderNo) {
        /*//1.创建查询交易请求对象
        QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
        queryOrderByOutTradeNoRequest.setMchid(wxPayV3Config.getMerchantId());
        queryOrderByOutTradeNoRequest.setOutTradeNo(orderNo);

        //2.创建调用微信服务端业务对象
        JsapiServiceExtension jsapiService = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();

        //3.调用微信查询交易状态接口
        Transaction transaction = jsapiService.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);

        //4.解析响应结果返回交易状态
        if (transaction != null) {
            Transaction.TradeStateEnum tradeState = transaction.getTradeState();
            if (Transaction.TradeStateEnum.SUCCESS == tradeState) {
                //用户支付成功
                return true;
            }
        }
        return false;*/

        //1.伪造微信交易对象
        Transaction transaction = new Transaction();
        transaction.setOutTradeNo(orderNo);
        transaction.setTransactionId("WX"+ IdUtil.getSnowflakeNextId());
        //修改支付记录状态
        paymentInfoService.updatePaymentInfoSuccess(transaction);
        return true;
    }
}
